package cn.weixin.song.controller.api;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.weixin.song.contant.R;
import cn.weixin.song.contant.R.ModelType;
import cn.weixin.song.controller.api.handle.MusicGameMsgHandle;
import cn.weixin.song.model.Activity;
import cn.weixin.song.model.App;
import cn.weixin.song.model.AppMenu;
import cn.weixin.song.model.User;
import cn.weixin.song.model.UserModelPlay;
import cn.weixin.song.model.WeixinWelcome;

import com.github.sd4324530.fastweixin.handle.MessageHandle;
import com.github.sd4324530.fastweixin.message.Article;
import com.github.sd4324530.fastweixin.message.BaseMsg;
import com.github.sd4324530.fastweixin.message.NewsMsg;
import com.github.sd4324530.fastweixin.message.TextMsg;
import com.github.sd4324530.fastweixin.message.req.BaseEvent;
import com.github.sd4324530.fastweixin.message.req.MenuEvent;
import com.github.sd4324530.fastweixin.message.req.TextReqMsg;
import com.github.sd4324530.fastweixin.servlet.WeixinSupport;
import com.google.common.collect.Lists;
import com.jcbase.core.util.PatternUtils;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;

public class MyWeixinSupport extends WeixinSupport{

	public final Log logger = LogFactory.getLog(getClass());
	
	private String wid;
	@Override
	protected String getToken() {
		App app=App.dao.getApp(wid);
		if(app!=null){
			return app.getToken();
		}
		return null;
	}
	public MyWeixinSupport(String wid){
		this.wid=wid;
	}
	@Override
	protected BaseMsg handleSubscribe(BaseEvent event) {
		User.dao.initUser(wid,event.getFromUserName());
		return new TextMsg(WeixinWelcome.dao.getWelcomeContents(R.ModelType.NONE));
	}
	
	@Override
	protected BaseMsg handleTextMsg(TextReqMsg msg) {
		User user=User.dao.initUser(wid,msg.getFromUserName());
		//替换掉中文类型的@#
		String content=msg.getContent().trim().replaceAll("＠", "@").replaceAll("＃", "#");
		if(content.contains("#")&&content.split("#").length==2){
			String[] arr=content.split("#");
			String realname=arr[0];
			String mobilephone=arr[1];
			if(realname.length()>10){
				return  new TextMsg("姓名长度不能大于20");
			}
			if(!PatternUtils.isMobileNO(mobilephone)){
				return  new TextMsg("手机号格式不对");
			}
			if(User.dao.mobileHasExist(user.getInt("id"), mobilephone)){
				return  new TextMsg("手机号已存在,请更换其他手机号");
			}
			User.dao.updateBaseInfo(user.getInt("id"),realname,mobilephone);
			return  new TextMsg("更新个人信息成功");
		}
		if(content.equals("9")){//个人信息
			return  new TextMsg("===个人信息===\r\n姓名:"+user.getStr("realname")+"\r\n手机号:"+user.getStr("mobilephone")+"\r\n剩余金币:"+user.getInt("gold_coin")+"\r\n发送\"姓名#手机号\"可更新信息");
		}
		if(content.startsWith("s@")&&content.length()>5){
			if(user.getInt("inviter_uid")==null){
				BaseMsg baseMsg=User.dao.beInvite(user.getInt("id"),content.substring(2));
				return baseMsg;
			}else{
				return  new TextMsg("你已经被邀请过了");
			}
		}
		if(msg.getContent().equals(R.ModelType.MUSIC.toString())){
			UserModelPlay.dao.updateModelPlayTime(R.ModelType.MUSIC, user.getId());
			return  new TextMsg(WeixinWelcome.dao.getWelcomeContents(ModelType.MUSIC));
		}
		if(msg.getContent().equals(R.ModelType.NONE.toString())){
			UserModelPlay.dao.updateModelPlayTime(R.ModelType.NONE, user.getId());
			return  new TextMsg(WeixinWelcome.dao.getWelcomeContents(ModelType.NONE));
		}
		return null;
	}
	
	@Override
	protected BaseMsg handleMenuClickEvent(MenuEvent event) {
		User.dao.initUser(wid,event.getFromUserName());
		AppMenu appMenu=AppMenu.dao.getByKey(event.getEventKey());
		//content有内容直接返回文本消息
		if(StrKit.notBlank(appMenu.getContent())){
			return new TextMsg(appMenu.getContent());
		}
		if(appMenu.getRefType()!=null&&appMenu.getRefType()>0){
			//判断菜单引用的类型
			if(appMenu.getRefType().equals(R.MenuRefType.activity)){//转盘活动
				Activity activity=Activity.dao.findById(appMenu.getRefId());
				if(activity!=null){
					List<Article> articles=Lists.newArrayList();
					Article article=new Article();
					article.setTitle(activity.getTitle());
					if(StrKit.notBlank(activity.getPicUrl())){
						article.setPicUrl(PropKit.get("static_url")+activity.getPicUrl());
					}
					article.setUrl(PropKit.get("wx_base_url")+"luck?aid="+appMenu.getRefId()+"&openid="+event.getFromUserName());
					article.setDescription(activity.getSummary());
					articles.add(article);
					return new NewsMsg(articles);
				}
				return null;
			}else if(appMenu.getRefType().equals(R.MenuRefType.my_coupon)){//查看我的优惠券
					List<Article> articles=Lists.newArrayList();
					Article article=new Article();
					article.setTitle("我的优惠券");
					article.setPicUrl("");
					article.setUrl(PropKit.get("wx_base_url")+"coupon?openid="+event.getFromUserName()+"&appId="+appMenu.getAppId());
					article.setDescription("点击查看");
					articles.add(article);
					return new NewsMsg(articles);
			}
		}
		return super.handleMenuClickEvent(event);
	}
	@Override
	protected List<MessageHandle> initMessageHandles() {
		// TODO Auto-generated method stub
		List<MessageHandle> list=Lists.newArrayList();
		list.add(new MusicGameMsgHandle(wid));
		return list;
	}
	
}
